package views;
import controllers.Driver;
import controllers.Permission;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableColumn;

import controllers.User;
import db.DriverDAO;
import db.PermissionDAO;

import db.UserDAO;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;

public class ViewUsersFrame extends JFrame {

	private static final int WIDTH=800;
	private static final int HEIGHT=500;
	private static final String TITLE = "View / Edit Users";
	private static Object[][] users;
	private static JButton delete, add, edit, save, clear;
	private static JTable table;
	private static java.util.List<User> list;
	private static DefaultTableModel model;
	private static JScrollPane scrollpane;
	private static Container c;
        private static Permission[] permissions;
        private static ArrayList<Permission> permissionsArray;
        private static Driver[] drivers;
        private static ArrayList<Driver> driversArray;
	private static int editRow;
        static int selectedIndex;

	public ViewUsersFrame(int xBound, int yBound){
		this.setBounds(xBound+100, yBound+50, WIDTH, HEIGHT);
		this.setResizable(false);
		this.setTitle(TITLE);
		
                permissionsArray = (ArrayList<Permission>)PermissionDAO.getPermissions();
		permissions = new Permission[permissionsArray.size()];
		for(int i=0;i<permissionsArray.size();i++){
			permissions[i] = permissionsArray.get(i);
		}

                driversArray = (ArrayList<Driver>)DriverDAO.getDrivers();
		drivers = new Driver[driversArray.size()];
		for(int i=0;i<driversArray.size();i++){
			drivers[i] = driversArray.get(i);
		}

		c = this.getContentPane();
		c.setLayout(null);


		scrollpane = new JScrollPane();
		c.add(scrollpane);
		updateRows();

		add = new JButton("Add");
		add.setBounds(25, 425, 100, 30);
		add.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				//new add user
			}
		});
		c.add(add);

		edit = new JButton("Edit");
		edit.setBounds(135, 425, 100, 30);
		edit.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				int row = table.getSelectedRow();
				if(row!=-1){
					//model.editRow(row);
					editRow = row;
					table.editCellAt(row, table.getSelectedColumn());
					table.getCellEditor().addCellEditorListener(new CellEditorListener(){
						@Override
						public void editingCanceled(ChangeEvent e) {
						}
						@Override
						public void editingStopped(ChangeEvent e) {
							save.setEnabled(true);
							edit.setEnabled(false);
						}
					});
				}
				else{
					System.out.println("Nothing Selected");
				}

			}
		});
		c.add(edit);

		delete = new JButton("Delete");
		delete.setBounds(245, 425, 100, 30);
		delete.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(JOptionPane.showConfirmDialog(getComponent(0), "Are you sure you want to delete? This cannot be undone", "Delete", 0)==0){
					int row = table.getSelectedRow();
					if(row!=-1){
						UserDAO.deleteUser(list.get(row));
						updateRows();
					}
					else{
						System.out.println("Nothing selected");
					}
				}
			}
		});

		c.add(delete);

		save = new JButton("Save");
		save.setBounds(355, 425, 100, 30);
		save.setEnabled(false);
		save.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				try{
					User temp = list.get(editRow);
					temp.setUsername(table.getValueAt(editRow, 0).toString());
					temp.setPassword(table.getValueAt(editRow, 1).toString());
                                        temp.setPermissionLevelID(permissions[selectedIndex].getId());
                                        temp.setDriverID(drivers[selectedIndex].getId());
                                        UserDAO.saveUser(temp);
                                        updateRows();
					save.setEnabled(false);
					edit.setEnabled(true);
				}
				catch(Exception e){
					e.printStackTrace();
					JOptionPane.showMessageDialog(getComponent(0), "Save Failed! Please make sure your changes are valid.","Save Failed!",0);
					updateRows();
					edit.setEnabled(true);
					save.setEnabled(false);
				}
			}
		});
		c.add(save);
		
		clear = new JButton("Clear");
		clear.setBounds(465, 425, 100, 30);
		clear.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				updateRows();
				edit.setEnabled(true);
				save.setEnabled(false);
			}
		});
		c.add(clear);

		this.setVisible(true);

	}

	public static void updateRows(){
		list = UserDAO.getUsers();
		users = new Object[list.size()][4];
		for(int i=0;i<list.size();i++){
			users[i][0] = list.get(i).getUsername();
			users[i][1] = list.get(i).getPassword();
			users[i][2] = list.get(i).getPermissionLevelDesc();
			users[i][3] = list.get(i).getDriverName();
		}

		Object columnNames[] = {"Username", "Password", "Permission Level", "Driver"};
		model = new DefaultTableModel(users, columnNames){
                    boolean[] editableColumns = new boolean[]{false, false, true, true};
                    @Override
                    public boolean isCellEditable(int row, int col){
                        if(row==editRow){
                            return editableColumns[col];
                        }
                        return false;
                    }
                };
		table = new JTable(model);
		table.setRowHeight(30);
		table.getTableHeader().setReorderingAllowed(false);
		TableColumn col = table.getColumnModel().getColumn(2);
		col.setCellEditor(new customPermissionsEditor(new JComboBox(permissions)));
                TableColumn col2 = table.getColumnModel().getColumn(3);
		col2.setCellEditor(new customDriversEditor(new JComboBox(drivers)));
		c.remove(scrollpane);
		scrollpane = new JScrollPane(table);
		scrollpane.setBounds(25,0,750,400);
		c.add(scrollpane);
	}


}

class customPermissionsEditor extends DefaultCellEditor{
	public customPermissionsEditor(final JComboBox arg0){
		super(arg0);
		this.addCellEditorListener(new CellEditorListener() {
			@Override
			public void editingStopped(ChangeEvent e) {
				ViewUsersFrame.selectedIndex = arg0.getSelectedIndex();
			}
			@Override
			public void editingCanceled(ChangeEvent e) {
				// TODO Auto-generated method stub
			}
		});
	}
}

class customDriversEditor extends DefaultCellEditor{
	public customDriversEditor(final JComboBox arg0){
		super(arg0);
		this.addCellEditorListener(new CellEditorListener() {
			@Override
			public void editingStopped(ChangeEvent e) {
				ViewUsersFrame.selectedIndex = arg0.getSelectedIndex();
			}
			@Override
			public void editingCanceled(ChangeEvent e) {
				// TODO Auto-generated method stub
			}
		});
	}
}
